package com.xiaonuoxi.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

/**
 * @Author: 小诺希
 * @Date: 2021-03-26 15:10
 * @Version v1.0
 */
@Component
public class MyHandler extends TextWebSocketHandler {


    @Autowired
    private SocketManager socketManager;

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message)
            throws IOException {
        String payload = message.getPayload();
        System.out.println("获取到消息 >> " + message.getPayload());

        // 向客户端发送消息
        session.sendMessage(new TextMessage("消息已收到"));
        if (payload.equals("size")){
            session.sendMessage(new TextMessage( "在线人数："+socketManager.WebsocketActiveNum().toString()));
        }

    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws
            Exception {


        Integer uid = (Integer) session.getAttributes().get("uid");
        socketManager.add(uid+"",session);
        session.sendMessage(new TextMessage(uid+", 你好！欢迎连接到ws服务"));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
            throws Exception {
        socketManager.removeBySession(session);
        System.out.println("断开连接！");
        System.out.println(session.getId());

    }
}
